package com.hyw.cm.server;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import com.hyw.cm.protocal.log.LoggingDuplexHandler;
import com.hyw.cm.protocal.service.IBusinessProtocalService;
import com.hyw.cm.reg.service.IEquipmentService;
import com.hyw.cm.server.config.ConnectionManagerConfig.ServerConfig;
import com.hyw.cm.server.storage.dao.IConnectionRepository;
import com.hyw.cm.session.pubsub.IPubSub;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.internal.PlatformDependent;

@Service
@EnableConfigurationProperties(value = { ServerConfig.class })
public class ConnectionManagerServerStarter implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(ConnectionManagerServerStarter.class);

    @Resource
    private IConnectionRepository connectionStorage;

    @Autowired
    private List<IBusinessProtocalService> services;

    @Resource
    private IEquipmentService equipmentService;

    @Resource
    private ServerConfig serverConfig;

    @Qualifier("sessionPubsub")
    @Autowired(required = false)
    private IPubSub sessionPubsub;

    @Override
    public void run(String... args) throws Exception {
        log.info("Connection Manager Server initialized with port(s):{}", serverConfig.getPort());

        EventLoopGroup bossGroup = PlatformDependent.isWindows() ? new NioEventLoopGroup(serverConfig.getIo())
                : new EpollEventLoopGroup(serverConfig.getIo());
        EventLoopGroup workerGroup = PlatformDependent.isWindows() ? new NioEventLoopGroup(serverConfig.getWorkers())
                : new EpollEventLoopGroup(serverConfig.getWorkers());

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(
                    PlatformDependent.isWindows() ? NioServerSocketChannel.class : EpollServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast("selftDefendIdleHandler",
                                    new ReadTimeoutHandler(10L, TimeUnit.SECONDS));
                            channel.pipeline().addLast("protocolDecoderRouter", new ProtocolDecoderRouter());
                            channel.pipeline().addLast("logging", new LoggingDuplexHandler());
                            channel.pipeline().addLast("businessHandler", new InnerBusinessHandler(services,
                                    equipmentService, connectionStorage, serverConfig.getId(), sessionPubsub));
                            channel.pipeline().addLast("protocolEncoderRouter", new ProtocolEncoderRouter());
                        }
                    });
            serverBootstrap.option(ChannelOption.SO_BACKLOG, serverConfig.getBacklog());
            serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, serverConfig.getConnectionTimeoutMills());

            serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, serverConfig.getKeepAlive());
            serverBootstrap.childOption(ChannelOption.TCP_NODELAY, serverConfig.getTcpNoDeplay());
            serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, serverConfig.getConnectionTimeoutMills());

            ChannelFuture f = serverBootstrap.bind(serverConfig.getPort());
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Interrupted!", e);
            Thread.currentThread().interrupt();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
